package com.borqsprocessmanager.db;

import java.util.HashMap;

import com.borqsprocessmanager.db.DBProvider.ProcessTable;
import com.borqsprocessmanager.db.DBProvider.WhiteListTable;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class ProcessContentProvider extends ContentProvider {

    private static HashMap<String, String> mProcessMap;
    private static HashMap<String, String> mWhiteMap;
    private static final int PROCESS = 1;
    private static final int PROCESS_ID = 2;

    private static final int WHITE = 3;
    private static final int WHITE_ID = 4;

    private static final UriMatcher mUriMatcher;

    private DBHelper mOpenHelper;

    @Override
    public boolean onCreate() {
        mOpenHelper = DBHelper.getInstance(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String orderBy;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理

        case PROCESS_ID:
            qb.appendWhere(ProcessTable._ID + "=?");
            selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
                    new String[] { uri.getLastPathSegment() });
        case PROCESS:
            qb.setTables(ProcessTable.TABLE_NAME);
            qb.setProjectionMap(mProcessMap);
            if (TextUtils.isEmpty(sortOrder)) {
                orderBy = ProcessTable.DEFAULT_SORT_ORDER;
            } else {
                orderBy = sortOrder;
            }
            break;
        case WHITE_ID:
            qb.appendWhere(WhiteListTable._ID + "=?");
            selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
                    new String[] { uri.getLastPathSegment() });
        case WHITE:
            qb.setTables(WhiteListTable.TABLE_NAME);
            qb.setProjectionMap(mWhiteMap);
            if (TextUtils.isEmpty(sortOrder)) {
                orderBy = WhiteListTable.DEFAULT_SORT_ORDER;
            } else {
                orderBy = sortOrder;
            }
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        switch (mUriMatcher.match(uri)) {
        case PROCESS:
            return DBProvider.CONTENT_TYPE;
        case PROCESS_ID:
            return DBProvider.CONTENT_ITEM_TYPE;
        case WHITE:
            return DBProvider.CONTENT_TYPE;
        case WHITE_ID:
            return DBProvider.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        ContentValues contentValues = null;
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String tableName = "";
        long rowId = 0;
        // String nullColumn = "";

        if (null != values) {
            contentValues = values;
        } else {
            contentValues = new ContentValues();
        }

        switch (mUriMatcher.match(uri)) {
        case PROCESS:
            tableName = ProcessTable.TABLE_NAME;
            rowId = db.insert(tableName, null, contentValues);
            break;
        case WHITE:
            tableName = WhiteListTable.TABLE_NAME;
            rowId = db.insert(tableName, null, contentValues);
            break;
        default:
            break;
        }
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(uri, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int numValues = 0;
        db.beginTransaction(); // 开始事务
        try {
            // 数据库操作
            numValues = values.length;
            for (int i = 0; i < numValues; i++) {
                insert(uri, values[i]);
            }
            db.setTransactionSuccessful(); // 别忘了这句 Commit
        } finally {
            db.endTransaction(); // 结束事务
        }
        return numValues;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String finalWhere;
        int count;
        switch (mUriMatcher.match(uri)) { // 这里要对不同表的匹配结果做不同处理，注意下面用到的表名不要弄错了
        case PROCESS:
            count = db
                    .delete(ProcessTable.TABLE_NAME, selection, selectionArgs);
            break;
        case PROCESS_ID:
            finalWhere = DatabaseUtils.concatenateWhere(ProcessTable._ID
                    + " = " + ContentUris.parseId(uri), selection);
            count = db.delete(ProcessTable.TABLE_NAME, finalWhere,
                    selectionArgs);
            break;
        case WHITE:
            count = db.delete(WhiteListTable.TABLE_NAME, selection,
                    selectionArgs);
            break;
        case WHITE_ID:
            finalWhere = DatabaseUtils.concatenateWhere(WhiteListTable._ID
                    + " = " + ContentUris.parseId(uri), selection);
            count = db.delete(WhiteListTable.TABLE_NAME, finalWhere,
                    selectionArgs);
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        String finalWhere;

        switch (mUriMatcher.match(uri)) {
        case PROCESS_ID:
            // If URI is for a particular row ID, update is based on
            // incoming
            // data but modified to restrict to the given ID.
            selection = DatabaseUtils.concatenateWhere(
                    DBProvider.ProcessTable._ID + " = "
                            + ContentUris.parseId(uri), selection);
        case PROCESS:
            // If URI is main table, update uses incoming where clause and
            // args.
            count = db.update(DBProvider.ProcessTable.TABLE_NAME, values,
                    selection, selectionArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        mUriMatcher.addURI(ProcessTable.AUTHORITY, ProcessTable.TABLE_NAME,
                PROCESS);
        mUriMatcher.addURI(ProcessTable.AUTHORITY, ProcessTable.TABLE_NAME
                + "/#", PROCESS_ID);

        mProcessMap = new HashMap<String, String>();
        mProcessMap.put(ProcessTable._ID, ProcessTable._ID);
        mProcessMap.put(ProcessTable.SAMPLE_ID, ProcessTable.SAMPLE_ID);
        mProcessMap.put(ProcessTable.IS_SYSTEM, ProcessTable.IS_SYSTEM);
        mProcessMap.put(ProcessTable.PID, ProcessTable.PID);
        mProcessMap.put(ProcessTable.UID, ProcessTable.UID);
        mProcessMap.put(ProcessTable.TYPE, ProcessTable.TYPE);
        mProcessMap.put(ProcessTable.PKG_NAME, ProcessTable.PKG_NAME);
        mProcessMap.put(ProcessTable.APPNAME_NAME, ProcessTable.APPNAME_NAME);
        mProcessMap.put(ProcessTable.PROCESS_NAME, ProcessTable.PROCESS_NAME);
        mProcessMap.put(ProcessTable.RATIO, ProcessTable.RATIO);
        mProcessMap.put(ProcessTable.RX_BYTES, ProcessTable.RX_BYTES);
        mProcessMap.put(ProcessTable.TX_BYTES, ProcessTable.TX_BYTES);
        mProcessMap.put(ProcessTable.TOTAL_BYTES, ProcessTable.TOTAL_BYTES);

        mUriMatcher.addURI(WhiteListTable.AUTHORITY, WhiteListTable.TABLE_NAME,
                WHITE);
        mUriMatcher.addURI(WhiteListTable.AUTHORITY, WhiteListTable.TABLE_NAME
                + "/#", WHITE_ID);

        mWhiteMap = new HashMap<String, String>();
        mWhiteMap.put(WhiteListTable._ID, WhiteListTable._ID);
        mWhiteMap.put(WhiteListTable.SAMPLE_ID, WhiteListTable.SAMPLE_ID);
        mWhiteMap.put(WhiteListTable.IS_SYSTEM, WhiteListTable.IS_SYSTEM);
        mWhiteMap.put(WhiteListTable.PID, WhiteListTable.PID);
        mWhiteMap.put(WhiteListTable.UID, WhiteListTable.UID);
        mWhiteMap.put(WhiteListTable.TYPE, WhiteListTable.TYPE);
        mWhiteMap.put(WhiteListTable.PKG_NAME, WhiteListTable.PKG_NAME);
        mWhiteMap.put(WhiteListTable.APP_NAME, WhiteListTable.APP_NAME);
        mWhiteMap.put(WhiteListTable.PROCESS_NAME, WhiteListTable.PROCESS_NAME);
        mWhiteMap.put(WhiteListTable.RATIO, WhiteListTable.RATIO);
        mWhiteMap.put(WhiteListTable.RX_BYTES, WhiteListTable.RX_BYTES);
        mWhiteMap.put(WhiteListTable.TX_BYTES, WhiteListTable.TX_BYTES);
        mWhiteMap.put(WhiteListTable.TOTAL_BYTES, WhiteListTable.TOTAL_BYTES);
    }
}
